import React, {useContext, useRef, useState} from "react";
import {
    View,
    TouchableOpacity, Alert,
} from "react-native";
import styles from "./index.style";
import {useTheme} from "@/contexts/ThemeContext";
import FontAwesome from "@expo/vector-icons/FontAwesome";
import {ChatDetailContext} from "@/components/Chat/ChatDetail";
import CustomEmojiList from "./CustomEmojiList";
import BuiltInEmojiList from "./BuiltInEmojiList";
import PagerView from "react-native-pager-view";
import {UserEmojiPackItemType} from "@/types/user-emoji";
import {cacheImageByUri} from "@/utils/file-utils";
import {ChatMessage, MessageStatus, MessageType} from "@/types/chat-message";
import {getSnowflakeId} from "@/utils/snow-flake-utils";
import {SessionType} from "@/types/chat-session";
import {useUserProfileState} from "@/hooks/user/user-profile";
import {useChatMessageActions} from "@/hooks/chat/chat-message";
import {useChatSessionActions} from "@/hooks/chat/chat-session";
import {extractLastMessageText} from "@/utils/message-utils";
import {useStompSend} from "@/hooks/stomp/stomp-send";

const tabItems = [
    {key: "emoji", icon:  <FontAwesome name="smile-o" size={24} color="gray"/>},
    {key: "custom", icon: <FontAwesome name="heart-o" size={24} color="gray"/>},
];

// 缓存表，用于存储已下载的表情图片路径
const emojiCacheMap = new Map<string, string>(); // fileId => localPath

const getCachedEmojiPath = async (fileId: string, localUri: string , serverUrl: string): Promise<string> => {
    if (emojiCacheMap.has(fileId)) {
        return emojiCacheMap.get(fileId);
    }
    const localPath = await cacheImageByUri(localUri, serverUrl);
    emojiCacheMap.set(fileId, localPath);
    return localPath;
};

export default function EmojiPanelDrawer() {
    const { colors } = useTheme();
    const [activeIndex, setActiveIndex] = useState(0);
    const pagerRef = useRef<PagerView>(null);
    const {flatListRef, inputText, setInputText , sessionId , sessionType} = useContext(ChatDetailContext)
    const {currentUser} = useUserProfileState();
    const {addMessage} = useChatMessageActions();
    const {updateSession} = useChatSessionActions();
    const {sendChatMessage} = useStompSend();

    const onPageSelected = (e: any) => {
        setActiveIndex(e.nativeEvent.position);
    };
    const handleTabPress = (index: number) => {
        setActiveIndex(index);
        pagerRef.current?.setPage(index);
    };

    const sendEmoji = async (emoji: UserEmojiPackItemType) => {
        const cachedFilePath = await getCachedEmojiPath(emoji.fileId, emoji.filePath, emoji.serverUrl);
        const message: ChatMessage<any, any> = {
            revokeStatus: false,
            system: false,
            messageId: getSnowflakeId(),
            sessionId,
            messageType: MessageType.EMOJI,
            content: {
                url: cachedFilePath,
                fileId: emoji.fileId,
            },
            user: {
                id: currentUser.id,
                avatar: currentUser.avatar,
                name: currentUser.nickname,
                updateTime: currentUser.updateTime,
            },
            status: sessionType === SessionType.SINGLE && sessionId === currentUser.id ?
                MessageStatus.SENT : // 自己发送给自己的消息状态为SENT
                MessageStatus.SENDING, // 发送给其他人的消息状态为SENDING
            createTime: new Date().getTime()
        };

        await addMessage(message);
        await updateSession({
            lastMessageId: message.messageId,
            lastMessage: extractLastMessageText(message.messageType , message.content),
            sessionId,
        });
        // 移动到最新消息
        flatListRef.current?.scrollToEnd({animated: true});
        message.content.url = emoji.serverUrl; // 确保使用服务器URL
        if (sessionType === SessionType.SINGLE && sessionId === currentUser.id) {
            return;
        }
        sendChatMessage({...message, sessionType});
    }

    return (
        <View style={[styles.panel,{ backgroundColor: colors.background }]}>
            {/* 顶部 TabBar */}
            <View style={[styles.tabBar, { borderColor: colors.border.divider }]}>
                {tabItems.map((item, index) => (
                    <TouchableOpacity
                        key={item.key}
                        onPress={() => handleTabPress(index)}
                        style={[styles.tabItem, activeIndex === index && styles.tabItemActive]}
                    >
                        {item.icon}
                    </TouchableOpacity>
                ))}
            </View>

            {/* 横向滑动 PagerView */}
            <PagerView
                style={{ flex: 1 }}
                initialPage={0}
                scrollEnabled={true}
                ref={pagerRef}
                onPageSelected={onPageSelected}
            >
                <View key="0">
                    <BuiltInEmojiList onSelectEmoji={(emoji) => setInputText(inputText + emoji)} />
                </View>
                <View key="1">
                    <CustomEmojiList  onSelectEmoji={sendEmoji}/>
                </View>
            </PagerView>
        </View>
    );
}
